<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.keyword" placeholder="关键字搜索"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="search">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="handleAdd">新增</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="danger" @click="onSale" :disabled="this.sels.length===0">上架</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="info" @click="offSale" :disabled="this.sels.length===0">下架</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <!--列表-->
        <el-table :data="products" highlight-current-row v-loading="listLoading"
                  @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="40">
            </el-table-column>
            <el-table-column prop="name" label="名称" width="160" sortable>
            </el-table-column>
            <el-table-column prop="costprice" label="成本" width="100" sortable>
            </el-table-column>
            <el-table-column prop="saleprice" label="售价" width="100" sortable>
            </el-table-column>
            <el-table-column prop="onsaletime" label="上架时间" width="120" sortable>
            </el-table-column>
            <el-table-column prop="offsaletime" label="下架时间" width="120" sortable>
            </el-table-column>

            <el-table-column prop="salecount" label="销量" width="120" sortable>
            </el-table-column>
            <el-table-column prop="state" label="状态" width="100" sortable>
                <template scope="scope">
                    <span style="color: red" v-if="scope.row.state == 0">下架</span>
                    <span style="color: green" v-else-if="scope.row.state == 1">上架</span>
                    <span style="color: grey" v-else>未知</span>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next"
                           @current-change="handleCurrentChange"
                           :page-size="pageSize"
                           :current-page="currentPage"
                           :total="total"
                           style="float:right;">
            </el-pagination>
        </el-col>

        <!--编辑界面
                    : '',
                    costprice: 0,
                    saleprice: 0,
                    salecount: 0,
                    detail:{
                        id:null,
                        intro:"",
                        orderNotice:""
                    }
        -->
        <el-dialog title="新增或编辑" :visible.sync="productFormVisible" :close-on-click-modal="false">
            <el-form :model="productForm" label-width="80px"
                     :rules="productFormRules"
                     ref="productForm">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="productForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="资源" prop="resources">
                    <!--<el-input v-model="productForm.resources" auto-complete="off"></el-input>-->
                    <el-upload
                            class="upload-demo"
                            action="http://localhost:8080/fastDfs/"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :on-success="handleSuccess"
                            :file-list="fileList"
                            list-type="picture">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="成本" prop="costprice">
                    <el-input v-model="productForm.costprice" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="售价" prop="saleprice">
                    <el-input v-model="productForm.saleprice" auto-complete="off"></el-input>
                </el-form-item>
                <!--<el-form-item label="销量" prop="salecount">
                    <el-input v-model="productForm.salecount" auto-complete="off"></el-input>
                </el-form-item>
                销量不可编辑修改增加
                -->
                <el-form-item label="简介" prop="intro">
                    <!--<el-input v-model="productForm.detail.intro" auto-complete="off"></el-input>-->
                    <quill-editor v-model="productForm.detail.intro"
                     :options="quillConfig">
                    </quill-editor>
                </el-form-item>
                <el-form-item label="预约须知" prop="orderNotice">
                    <!--<el-input v-model="productForm.detail.orderNotice" auto-complete="off"></el-input>-->
                    <quill-editor v-model="productForm.detail.orderNotice"
                                  :options="quillConfig">
                    </quill-editor>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="productFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="productSubmit" :loading="productLoading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import { quillEditor } from "vue-quill-editor"; //调用编辑器
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';
    //引入 quill-config.js
    import quillConfig from "../../common/js/quill-config"


    export default {
        components: {
            quillEditor
        },
        data() {
            return {
                quillConfig:quillConfig,
                filters: {
                    keyword: ''
                },
                products: [],
                fileList: [],
                total: 0,
                currentPage: 1,
                pageSize: 6,
                listLoading: false,
                sels: [],//列表选中行

                productFormVisible: false,//编辑界面是否显示
                productLoading: false,//提交按钮忙等
                productFormRules: {//表单校验规则
                    name: [
                        {required: true, message: '请输入名称', trigger: 'blur'}
                    ],
                    sn: [
                        {required: true, message: '请输入编号', trigger: 'blur'}
                    ]
                },

                //编辑界面数据
                productForm: {//表单模型数据
                    id: null,
                    name: "",
                    resources: null,
                    costprice: 0,
                    saleprice: 0,
                    salecount: 0,
                    detail: {
                        id: null,
                        intro: "",
                        orderNotice: ""
                    }
                }
            }
        },
        methods: {
            onSale(){
                var ids = this.sels.map(item => item.id);
                //获取选中的行
                if(!this.sels || this.sels.length  <1){
                    this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
                    return;
                }
                this.$confirm('确认上架选中记录吗？', '温馨提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.patch('/product/onsale',ids).then((res) => {
                        this.listLoading = false;

                        if(res.data.success){
                            this.$message({
                                message: '上架成功',
                                type: 'success'
                            });
                        }else{
                            this.$message({
                                message: res.data.message,
                                type: 'error'
                            });
                        }
                        this.getProducts();
                    });
                }).catch(() => {

                });
            },
            offSale(){

                var ids = this.sels.map(item => item.id);
                //获取选中的行
                if(!this.sels || this.sels.length  <1){
                    this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
                    return;
                }
                this.$confirm('确认下架选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.patch('/product/offsale',ids).then((res) => {
                        this.listLoading = false;

                        if(res.data.success){
                            this.$message({
                                message: '下架成功',
                                type: 'success'
                            });
                        }else{
                            this.$message({
                                message: res.data.message,
                                type: 'error'
                            });
                        }
                        this.getProducts();
                    });
                }).catch(() => {

                });
            },
            handleSuccess(response, file, fileList){
                console.log(response);
                console.log("===========")
                console.log("上传成功后返回的" + fileList);
                console.log(fileList[0]);
                //resultObj 文件的服务器地址，放到数据库中
                //根据双向绑定 logo 就有值 1,2,3
                let resourcesTmp = '';
                if(fileList!=null && fileList.length>0){
                    for(var i=0;i<fileList.length;i++){
                        if(i==0){
                            resourcesTmp = resourcesTmp+fileList[i].response.resultObj;
                        }else{
                            resourcesTmp = resourcesTmp+","+fileList[i].response.resultObj;
                        }
                    }
                }
                this.productForm.resources = resourcesTmp;
            },
            handleRemove(file, fileList) {
                console.log(file.response.resultObj);
                var filePath = file.response.resultObj;
                this.$http.delete("/fastDfs/?path=" + filePath)
                    .then(res => {
                        if (res.data.success) {
                            this.$message({
                                message: '删除成功!',
                                type: 'success'
                            });
                            let resourcesTmp= "";
                            for (let i = 0; i < fileList.length; i++) {
                                //如果是最后一个值，就不要加,
                                if (i == fileList.length - 1) {
                                    resourcesTmp+= fileList[i].response.resultObj;
                                } else {//如果不是就要加逗号
                                    resourcesTmp+= fileList[i].response.resultObj + ",";
                                }
                            }
                            this.productForm.resources = resourcesTmp;
                        } else {
                            this.$message({
                                message: '删除失败!',
                                type: 'error'
                            });
                        }
                    })
            },
            handlePreview(file) {
                console.log(file);
            },
            search() {//只要是高级查询按钮一点击
                this.currentPage = 1;//定位到第一页
                this.getProducts();
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getProducts();
            },
            //获取服务列表
            getProducts() {
                let para = {
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    keyword: this.filters.keyword
                };
                this.listLoading = true;//开启忙等框
                this.$http.post("/product", para)
                    .then(result => {
                        result = result.data;// pageList
                        this.products = result.list;
                        this.total = result.count;
                        this.listLoading = false;

                    })
                    .catch(result => {
                        alert("系统错误！");
                    })
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '温馨提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;//开启忙等框
                    this.$http.delete("/product/del/"+row.id)
                        .then(res => {
                            this.listLoading = false;//关闭忙等框
                            //???  该完成什么事情
                            res = res.data;//AjaxResult {success:true,message:"操作成功"}
                            //AjaxResult {success:false,message:"操作失败"}
                            if (res.success) {
                                this.$message({
                                    message: res.message,
                                    type: 'success'
                                });
                                this.currentPage = 1;//定位到第一页
                                this.getProducts();
                            } else {
                                this.$message({
                                    message: res.message,
                                    type: 'error'
                                });
                            }
                        })
                        .catch(result => {
                            console.log(result);
                            alert("系统错误！");
                        })
                }).catch(() => {

                });
            },
            //显示编辑界面

            handleEdit: function (index, row) {
                alert(11111)
                this.fileList = [];
                this.productForm = {};
                row.detail = {};//由于拷贝是深度拷贝
                this.productForm = Object.assign({}, row);//拷贝对象（回显）
                let resources = row.resources;
                if (resources) {
                    let resourecArry = resources.split(",");
                    for (let i = 0; i < resourecArry.length; i++) {
                        this.fileList.push(
                             {"url": "http://47.95.117.210:8888" + resourecArry[i],
                                "response":{"resultObj":resourecArry[i]}
                             }
                            );
                    }
                }

                // 在点击编辑的时候，触发加载详情数据
                this.$http.get("/product/detail/" + row.id)
                    .then(result => {
                        if (result.data) {
                            this.productForm.detail.intro = result.data.detail.intro;
                            this.productForm.detail.orderNotice = result.data.detail.orderNotice;
                        } else {
                            this.productForm.detail = {};
                        }
                        this.productFormVisible = true;//显示模态框
                    }).catch(result => {
                    this.$message({
                        message: '系统错误！',
                        type: 'success'
                    });
                });

            },
            //显示新增界面
            handleAdd: function () {
                this.fileList = [];
                this.productFormVisible = true;//显示模态框
                this.productForm = {//清空历史数据，不要ID
                    id: null,
                    name: "",
                    resources: null,
                    costprice: 0,
                    saleprice: 0,
                    salecount: 0,
                    detail: {
                        id: null,
                        intro: "",
                        orderNotice: ""
                    }
                };
                /*重置表单校验*/
                this.$refs['productForm'].resetFields();
            },
            //编辑提交按钮
            productSubmit: function () {
                /*拿到当前vue里面的所有ref，从里面找到 productForm*/
                this.$refs.productForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '温馨提示', {})
                            .then(() => {
                                this.productLoading = true;
                                //准备表单数据提交给后台
                                let para = Object.assign({}, this.productForm);
                                console.log(para);
                                alert(para.resources);
                                this.$http.put("/product/edit", para)
                                    .then(result => {
                                        //关闭忙等框
                                        this.productLoading = false;
                                        result = result.data;
                                        if (result.success) {
                                            //NProgress.done();
                                            this.$message({
                                                message: '提交成功',
                                                type: 'success'
                                            });
                                            /*重置表单校验*/
                                            this.$refs['productForm'].resetFields();
                                            this.productFormVisible = false;
                                            /*刷新页面*/
                                            this.currentPage = 1;//定位到第一页
                                            this.getProducts();
                                        } else {
                                            this.$message({
                                                message: result.message,
                                                type: 'error'
                                            });
                                        }
                                    });
                            }).catch(result => {
                            this.productLoading = false;
                            console.log(result);
                            alert("系统错误！");
                        });
                    }
                });
            },
            selsChange: function (sels) {
                /*现目前已经选中的所有行的数据*/
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id);//[1,5]
                this.$confirm('确认删除选中记录吗？', '温馨提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;//开启忙等框
                    this.$http.patch("/dept", ids)
                        .then(result => {
                            this.listLoading = false;//关闭忙等框
                            result = result.data;
                            if (result.success) {
                                this.$message({
                                    message: result.message,
                                    type: 'success'
                                });
                                this.currentPage = 1;//定位到第一页
                                this.getProducts();
                            } else {
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
                            }
                        })
                        .catch(result => {
                            console.log(result);
                            alert("系统错误！");
                        })
                }).catch(() => {

                });
            }
        },
        mounted() {
            /*页面加载完成触发*/
            this.getProducts();
        }
    }

</script>

<style scoped>

</style>